package net.comm.util;

import net.comm.common.Decode;
import java.io.*;
import java.sql.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

public class Function {

  public Function() {
  }
  /************************************************************************
*************************************************************************
函数功能：加密保存文本
参数设置：strMsg:      报文内容
          strFileName: 报文文件名
返回值：  0-成功,  -1: 失败
*************************************************************************
************************************************************************/
  public static int SaveMsgFile(String strMsg,String strFileName)
  {
     String strBakFile;
     String pathname="";
     //char MsgFileContent[]=new char[10001];
     if (strFileName.lastIndexOf("/")>0)
     {
    	 pathname=strFileName.substring(0,strFileName.lastIndexOf("/"));
    	 File f2=new File(pathname);
    	 if  (!f2.isDirectory() || !f2.exists())
         {
    		 f2.mkdir();
         }
     }
     File f1=new File(strFileName);
     if (strFileName=="")
        return -1;
     if  (f1.exists())
     {
     //2003.08.19 改变做法，如文件已存在，则原文件更名为 *.bak
     //rename==0,成功；==-1 失败，
     //失败时：errno=EEXIST	Permission denied: file already exists.
     //              ENOENT	No such file or directory
     //              ENOTSAM	Not same device
       strBakFile = strFileName + ".Bak";
       File f2=new File(strBakFile);
       if (f2.exists()) f2.delete();
       if (f1.renameTo(new File(strBakFile))==false)
       {
         System.out.println("报文 " + strFileName + " 已存在，且更名 *.Bak 失败！");
       }
     }

     //MsgFileContent=strMsg.toCharArray();
    // String strMsgencoded=net.swift.common.PublicFunction.Encode(new String(MsgFileContent),MsgFileContent.length);   //数据加密后再保存成文本
    //String strMsgencoded=net String(MsgFileContent);
    //补满位数;
    char startchar='\u0001';
    char endchar='\u0003';
    if (!strMsg.startsWith(String.valueOf(startchar)))
    strMsg=String.valueOf(startchar)+strMsg;
    if (!strMsg.endsWith(String.valueOf(endchar)))
    strMsg=strMsg+String.valueOf(endchar);
    int len=strMsg.length();
    int modlen=len % 512;
    for (int i=0;i<512-modlen;i++)
    {
       strMsg+=" ";
    }
    try{
      strMsg=Decode.Encode(strMsg);
    }
    catch(Exception e1)
    {
    	e1.printStackTrace();
    	return -1;
    }
    PrintWriter pw=null;
    try{
       pw= new PrintWriter(new FileOutputStream(f1));
       pw.print(strMsg);

     }
     catch(Exception e)
     {
       e.printStackTrace();
       return -1;
     }
     finally{
       pw.close();
     }
     return 0;
  }
  //保存原文到绝对路径下面不按日期存放
  public static int SaveSrcMsgFile(String strMsg,String strFileName)
  {
     String strBakFile;
     //char MsgFileContent[]=new char[10001];
     File f1=new File(strFileName);
     if (strFileName=="")
        return -1;
     if  (f1.exists())
     {
     //2003.08.19 改变做法，如文件已存在，则原文件更名为 *.bak
     //rename==0,成功；==-1 失败，
     //失败时：errno=EEXIST	Permission denied: file already exists.
     //              ENOENT	No such file or directory
     //              ENOTSAM	Not same device
       strBakFile = strFileName + ".Bak";
       File f2=new File(strBakFile);
       if (f2.exists()) f2.delete();
       if (f1.renameTo(new File(strBakFile))==false)
       {
         System.out.println("报文 " + strFileName + " 已存在，且更名 *.Bak 失败！");
       }
     }

     //MsgFileContent=strMsg.toCharArray();
    // String strMsgencoded=net.swift.common.PublicFunction.Encode(new String(MsgFileContent),MsgFileContent.length);   //数据加密后再保存成文本
    //String strMsgencoded=net String(MsgFileContent);
    //补满位数;
    char startchar='\u0001';
    char endchar='\u0003';
    strMsg=String.valueOf(startchar)+strMsg+String.valueOf(endchar);
    int len=strMsg.length();
    int modlen=len % 512;
    for (int i=0;i<512-modlen-1;i++)
    {
       strMsg+=" ";
    }
   /* try{
      strMsg=Decode.Encode(strMsg);
    }
    catch(Exception e1)
    {
    	e1.printStackTrace();
    	return -1;
    }*/
    PrintWriter pw=null;
    try{
       pw= new PrintWriter(new FileOutputStream(f1));
       pw.println(strMsg);
     }
     catch(Exception e)
     {
       e.printStackTrace();
       return -1;
     }
     finally{
       pw.close();
     }
     return 0;
  }
  //用于Servlet中定义页面的头部
  public static StringBuffer getHtmlHead(String title,String background,String[] jssrcs)
  {
	     StringBuffer htmlhead=new StringBuffer("");
	     htmlhead.append("<html>\n<head>\n");
//	     htmlhead.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
	     htmlhead.append("<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" %>");
	     htmlhead.append("<title>");
	     htmlhead.append(StringUtil.cnCodeTrans(title));
	     htmlhead.append("</title>");
	     if (jssrcs!=null)
	     {
	        for (int i=0;i<jssrcs.length;i++)
	        {
	           htmlhead.append("<script src=\"");
	           htmlhead.append(jssrcs[i]);
	           htmlhead.append("\"></script>");
	        }
	     }
	     htmlhead.append("</head>");
	     htmlhead.append("<body background=\"");
	     htmlhead.append(background);
	     htmlhead.append("\">");
	     return htmlhead;
  }
  public static String GetIpAddr(HttpServletRequest request) {
	  
	  String ip = request.getHeader("x-forwarded-for");
	
	  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("Proxy-Client-IP");
	  }
	  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("WL-Proxy-Client-IP");
	  }
	  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr();
	  }
	  return ip;
  } 
  
  public static void main(String[] args)
  {

	  
  }
  
}
  //启停后台服务sid为SRVCTRL表中的ID，act为处理方式
 /* public static String execcmd(String sid,String act1,String strcmd,Connection conn)
  {
    //如果是停止操作的话
    tab_srvctrl srvctrl = new tab_srvctrl();
    srvctrl._conn=conn;
    Runtime runtime = null;
    if (act1.equals("tz") || act1.equals("qztz") || act1.equals("qd")) {
      try {
        srvctrl.serviceid = sid;
        srvctrl.selectByPK();
        if (srvctrl._errorcode == 100)return "此服务不存在";
        else if (srvctrl._errorcode <0)return "查询此服务失败,请重试!";
      }
      catch (Exception e) {
        return "要处理的服务不存在!错误信息:"+e.getMessage();
      }
    }
    try {
      runtime = Runtime.getRuntime();
    }
    catch (Exception e) {
      return "启动服务运行环境失败,请联系技术员重新启动TOMCAT服务!错误信息:"+e.getMessage();
    }
    if (act1.equals("tz")) {
      srvctrl.operate = "C";
      try {
        srvctrl.updateByPK();
        if (srvctrl._errorcode != 0) {
          //runtime.runFinalization();
          //runtime.exit(0);
          return "更新停止标志位失败!";
        }
      }
      catch (Exception e) {
       // runtime.runFinalization();
        //runtime.exit(1);
        return "更新停止标志位失败!错误信息:"+e.getMessage();
      }
      if (srvctrl.serviceid.trim().equals("RECVFROMDCC") ||
          srvctrl.serviceid.trim().equals("SENDTODCC") ||
          srvctrl.serviceid.trim().equals("QUERYDCC") ||
          srvctrl.serviceid.trim().equals("SERVICES")) {
        String mycmd = "";
        if (srvctrl.serviceid.trim().equals("RECVFROMDCC"))
          mycmd = "kill_recvfromdqz.sh";
        else if (srvctrl.serviceid.trim().equals("SENDTODCC"))
          mycmd = "kill_sendtodqz.sh";
        else if (srvctrl.serviceid.trim().equals("QUERYDCC"))
          mycmd = "kill_qrydqz.sh";
        else if (srvctrl.serviceid.trim().equals("SERVICES"))
          mycmd = "stopservices";
        try {
          runtime.exec(mycmd,null);
         // runtime.runFinalization();
         // runtime.exit(0);
        }
        catch (Exception e) {
          //runtime.runFinalization();
          //runtime.exit(1);
          return "运行停止后台服务的SHELL失败!错误信息:"+e.getMessage();
        }
      }
    }
    else if (act1.equals("qztz")) {
      srvctrl.operate = "C";
      srvctrl.runflag = "P";
      try {
        srvctrl.updateByPK();
        if (srvctrl._errorcode != 0) {
          //runtime.runFinalization();
          //runtime.exit(0);
          return "更新强制停止标志位失败!";
        }
      }
      catch (Exception e) {
        //runtime.runFinalization();
       // runtime.exit(1);
        return "更新强制停止标志位失败!错误信息:"+e.getMessage();
      }
    }
    else if (act1.equals("qd")) {
      srvctrl.operate = "O";
      try {
        srvctrl.updateByPK();
        if (srvctrl._errorcode != 0) {
          //runtime.runFinalization();
          //runtime.exit(0);
          return "更新启动标志位失败!";
        }
      }
      catch (Exception e) {
        //runtime.runFinalization();
        //runtime.exit(1);
        return "更新启动标志位失败!错误信息:"+e.getMessage();
      }
      try {
        String cmd = strcmd + " " + sid;
        runtime.exec(cmd,null);
        //runtime.runFinalization();
       // runtime.exit(0);
      }
      catch (Exception e) {
       // runtime.runFinalization();
        //runtime.exit(1);
        return "启动后台服务失败!错误信息:"+e.getMessage();
      }
    }
    else { //检查服务状态
      try {
        Process p=runtime.exec("checkservices",null);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String ls_1="";
        while ( (ls_1=bufferedReader.readLine()) != null)
        System.out.println(ls_1);
        p.waitFor();
        //runtime.runFinalization();*/

